/**
 *  The Yz.Upload prototype
 *  Assuming "this"
 *
 */
(function() {
//    alert("A");
    var Yz = window.Yz;
    if (! (Yz instanceof Function)) {
        throw "Failed to identify the root Yz object";
    }

    Yz.Upload = function(elName, action, success, failure)
    {
        return this.init(elName, action, success, failure);
    };

    // notify the root Yz object that we have loaded
    Yz.loadedClasses["Yz.Upload"] = Yz.Upload;


    /****************************
     *      Implementation      *
     ****************************/


    /**
     *  @access private
     *  @var Object/Hash { formName: handler }
     */
    Yz.Upload.handlers = {};
    Yz.Upload.form = null;
    Yz.Upload.timer = false;
    Yz.Upload.currentHandler = false;

    /**
     *  @param Object args:
     *      elName: string [REQUIRED]
     *      action: string [REQUIRED]
     *      success: function
     *      failure: function
     *  @return handler
     *
     */
    Yz.Upload.createUpload = function(args)
    {
        var elName;
        if ("elName" in args) {
            elName = args.elName;
        } else {
            throw "Missing handler ID";
        }

        var action;
        if ("action" in args) {
            action = args.action;
        } else {
            throw "Missing Action";
        }

        var success = false;
        if ("success" in args) {
            // TODO add callback
            success = args.success;
        }
        var failure = false;
        if ("failure" in args) {
            failure = args.failure;
        }

        var handler = Yz.Upload.handlers[elName];
        if (! handler) {
            handler = new Yz.Upload(elName, action, success, failure);
            Yz.Upload.handlers[elName] = handler;
        }
        return handler;
    }

    /** call this static method when file uploaded successfully
     *  @param string formName
     *  @param string message
     */
    Yz.Upload.uploadComplete = function(filedata)
    {
        var handler = Yz.Upload.currentHandler;
        if (! handler) {
            throw "Invalid handler ID";
        }
        handler.complete(filedata);
        return Yz.Upload;
    }
    Yz.Upload.uploadFailed = function(elName, message)
    {
        var handler = Yz.Upload.currentHandler;
        if (! handler) {
            throw "Invalid handler ID";
        }
        handler.fail(message);
        return Yz.Upload;
    }

    Yz.Upload.createForm = function()
    {
        if (! Yz.Upload.form) {
            var div = document.createElement("DIV");
            div.innerHTML = "<form enctype='multipart/form-data' action='' method='POST' target='YzUploadFrame'>"
                + "<input type='file' name='theUpload' />"
                + "</form>"
                + "<iframe name='YzUploadFrame' id='YzUploadFrame' src='about:blank'"
                + ' style="border: 1px solid red; width: 100px; height: 100px"'
                + "></iframe>"
                ;
            Yz.Upload.form = {
                theDiv: div,
                theForm: div.getElementsByTagName("FORM")[0],
                theInput: div.getElementsByTagName("INPUT")[0]
            };
        }
        return Yz.Upload.form;
    }



    Yz.Upload.prototype = {
        input: false,
        form: false,

        /**
        *  Show a dialog with the form and iframe
        *  @access private
        *  @return Yz.Upload
        */
        showDialog: function(link)
        {
            console.log("showDialog");
            if (! this.form) {
                var form = Yz.Upload.createForm();
                this.input = form.theInput;
                this.form = form.theForm;
                console.log("input:" + this.input);
            }

            this.input.value = "";
            this.form.setAttribute("action", this.action);

            var self = this;
            var buttons = {};
            buttons[$(link).text()] = function() { self.submit(); }
            buttons["Cancel"] = function() { $(this).dialog("close"); }
            $(form.theDiv).dialog({
                modal: true,
                title: $(link).attr("title"),
                buttons: buttons
            });
            return this;
        }
        ,
        /**
        *
        *  the modified constructor: multiton, by form name
        *  Arguments: object {formName, inputName, success, failure}
        */
        init: function(elName, action, success, fail)
        {
            this.elName = elName;
            this.action = action;
            this.successCallback = success;
            this.failureCallback = fail;
            return this;
        }
        ,

        /**
        *  the "user" function
        *
        */
        submit: function()
        {
            console.log("input:" + this.input.name);
            if ( this.input.value ) {
                this.startTimer()
                    && this.form.submit();
            } else {
                Yz.Alert( "Файл не выбран" );
            }
            return false;
        }
        ,

        startTimer: function()
        {
            console.log("start timer: " + Yz.Upload.timer);
            if ( false !== Yz.Upload.timer ) {
                // prevent multiple simultaneous file uploads
                Yz.Alert( "Подождите, идёт загрузка..." );
                return false;
            }
            Yz.Upload.timer = setTimeout( this.timeout, 60000 );
            Yz.Upload.currentHandler = this;
            Yz.block();
            return true;
        }
        ,
        timeout: function()
        {
            Yz.Alert( "Upload timeout" );
            return Yz.Upload.currentHandler.done();
        }
        ,
        complete: function( filedata )
        {
            if ( this.successCallback ) {
                this.successCallback(filedata);
            }
            Yz.Alert( "Загрузка успешно произведена." );
            return this.done();
        }
        ,
        fail: function( errorMessage )
        {
            Yz.Alert( errorMessage );
            if ( this.failureCallback ) {
                this.failureCallback(errorMessage);
            }
            return this.done();
        }
        ,
        done: function()
        {
            if ( false !== Yz.Upload.timer ) {
                clearTimeout( Yz.Upload.timer );
            }
            Yz.Upload.currentHandler = false;
            Yz.Upload.timer = false;
            Yz.unblock();
            //Yz.Alert("Done");
            return this;
        }
    } // end prototype

})();

